﻿<MudDataGrid T="Fruit" @ref="_dataGrid" Items="@_fruits" Filterable="true" Hideable="true" Groupable="@_groupable"
GroupExpanded="true" RowContextMenuClick="@OnRowContextMenuClick">
    <ToolBarContent>
        <MudText Typo="Typo.h6">Fruits</MudText>
        <MudSpacer />
    </ToolBarContent>
    <Columns>
        <PropertyColumn Property="x => x.Name" Title="Name" Filterable="false" Groupable="false" />
        <PropertyColumn Property="x => x.Count" />
        <PropertyColumn Property="x => x.Category" Title="Category" Groupable="true" Grouping="true" GroupBy="@_groupBy">
            <GroupTemplate>
                <span style="font-weight:bold">Category: @context.Grouping.Key</span>
            </GroupTemplate>
        </PropertyColumn>
    </Columns>
</MudDataGrid>

<div class="d-flex flex-wrap mt-4">
    <MudButton Class="expand-all" OnClick="@ExpandAllGroups" Color="@Color.Primary">Expand All</MudButton>
    <MudButton OnClick="@CollapseAllGroups" Color="@Color.Primary">Collapse All</MudButton>
    <MudButton Class="add-button" OnClick="@AddFruit" Color="@Color.Primary">Add Fruit</MudButton>
    <MudButton Class="toggle-groupable" OnClick="@(() => _groupable = !_groupable)" Color="@Color.Primary">Toggle Groupable</MudButton>
</div>

@code {
    private bool _groupable;
    private MudDataGrid<Fruit> _dataGrid = null!;
    private readonly List<Fruit> _fruits =
    [
        new Fruit("Apple", 2, "Pome"),
        new Fruit("Pear", 4, "Pome"),
        new Fruit("Orange", 4, "Citrus")
    ];
    private readonly Func<Fruit, object> _groupBy = x => x.Category;

    [Parameter]
    public bool Groupable { get; set; } = true;

    public bool RowContextMenuClicked { get; set; }

    protected override void OnParametersSet()
    {
        base.OnParametersSet();
        _groupable = Groupable;
    }

    public void AddFruit()
    {
        _fruits.Add(new Fruit("Banana", 5, "Musa"));
    }

    public Task ExpandAllGroups()
    {
        return _dataGrid.ExpandAllGroupsAsync();
    }

    public Task CollapseAllGroups()
    {
        return _dataGrid.CollapseAllGroupsAsync();
    }

    private void OnRowContextMenuClick(DataGridRowClickEventArgs<Fruit> args)
    {
        RowContextMenuClicked = true;
    }

    public class Fruit(string name, int count, string category)
    {
        public string Name { get; set; } = name;

        public int Count { get; set; } = count;

        public string Category { get; set; } = category;
    }
}
